package com.hmall.item.web;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmall.common.PageDTO;
import com.hmall.constants.MQConstants;
import com.hmall.item.Item;
import com.hmall.item.service.IItemService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.security.InvalidParameterException;
import java.util.Date;

@RestController
@RequestMapping("item")
public class ItemController {


    @Autowired(required = false)
    private IItemService itemService;

    @Autowired(required = false)
    private RabbitTemplate rabbitTemplate;


    /**
     * 根据id查询商品
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Item findById(@PathVariable("id") Long id) {
        return itemService.getById(id);
    }

    /**
     * 商品分页查询
     *
     * @param page
     * @param size
     * @return
     */
    @GetMapping("/list")
    public PageDTO selectItem(
            @RequestParam(value = "page", defaultValue = "1") Integer page,
            @RequestParam(value = "size", defaultValue = "5") Integer size
    ) {
        Page<Item> result = itemService.page(new Page<Item>(page, size));
        return new PageDTO(result.getTotal(), result.getRecords());

    }

    /**
     * 新增商品
     *
     * @param item
     */
    @PostMapping
    public void insertItem(@RequestBody Item item) {
        item.setSold(0);
        item.setCommentCount(0);
        item.setStatus(1);
        item.setCreateTime(new Date());
        item.setUpdateTime(new Date());
        itemService.save(item);
        rabbitTemplate.convertAndSend(MQConstants.ITEM_EXCHANGE, MQConstants.ITEM_INSERT_KEY, item.getId());

    }

    /**
     * 商品上架下架功能
     *
     * @param id
     * @param status
     */
    @PutMapping("/status/{id}/{status}")
    public void updateItemStatus(@PathVariable("id") Long id, @PathVariable("status") Integer status) {
        Item item = itemService.getById(id);
        item.setStatus(status);
        itemService.updateById(item);
        rabbitTemplate.convertAndSend(MQConstants.ITEM_EXCHANGE, MQConstants.ITEM_INSERT_KEY, id);
    }


    /**
     * 修改商品数据
     *
     * @param item
     */
    @PutMapping()
    public void updateById(@RequestBody Item item) {
        if (item.getId() == null) {
            throw new InvalidParameterException("id不能为空");
        }
        itemService.updateById(item);
        rabbitTemplate.convertAndSend(MQConstants.ITEM_EXCHANGE, MQConstants.ITEM_INSERT_KEY, item.getId());
    }

    /**
     * 根据id删除商品
     *
     * @param id
     */
    @DeleteMapping("/{id}")
    public void deleteById(@PathVariable("id") Long id) {
        itemService.removeById(id);
        rabbitTemplate.convertAndSend(MQConstants.ITEM_EXCHANGE, MQConstants.ITEM_DELETE_KEY, id);
    }

}
